package com.capgemini.remind.controller;

import com.capgemini.core.AjaxResponse;
import com.capgemini.core.PageList;
import com.capgemini.interceptor.DealerNumUtils;
import com.capgemini.remind.pojo.*;
import com.capgemini.remind.service.*;
import com.capgemini.wechat.service.SaleOrderService;
import com.capgemini.wechat.service.VehicleService;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

@Controller
@RequestMapping("/remind/service")
public class RemindController {
	// 日志记录器
	public final Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private RemindService remindService;
	@Autowired
	private RemindSmsService remindSmsService;
	@Autowired
	private CustomerGroupService customerGroupService;
	@Autowired
	private CommonsService commonsService;
	@Autowired
	private RemindSendInfoService remindSendInfoService;
	@Autowired
	private ConsumeInfoService consumeInfoService;
	@Autowired
	private SaleOrderService saleOrderService;
	@Autowired
	private DealerPromotionPrivilege dealerPromotionPrivilege;
	@Autowired
	private DealerPromotionPrivilegeService dealerPromotionPrivilegeService;
	@Autowired
	private VehicleService vehicleService;

	@RequestMapping("/manage/{dealerNum}")
	public Object manage(@PathVariable("dealerNum") String dealerNum1
			, @RequestParam(name = "maintenanceItem", required = false) String maintenanceItem
			, @RequestParam(name = "send", required = false) String sendFlag
			, @RequestParam(name = "remindMonth", required = false) String remindMonth
	) {
		String dealerNum = DealerNumUtils.getDealerNum();

		ModelAndView mv = new ModelAndView("/remind/remind.jsp");

		mv.addObject("dealerNum", dealerNum);
		mv.addObject("send", sendFlag);
		mv.addObject("maintenanceItem", maintenanceItem);
		mv.addObject("remindMonth",remindMonth);
		//短信余额
//		Long smsQuantity = remindSmsService.querySmsQuantityByDealerNum(dealerNum);
		Long smsQuantity = null;
		mv.addObject("smsQuantity", smsQuantity);

		//客户分类
		CustomerGroup customerGroup = new CustomerGroup();
		customerGroup.setDealerId(dealerNum);
		customerGroup.setIsSR(true);

		List<CustomerGroup> customerGroups = customerGroupService.queryList(customerGroup);
		mv.addObject("customerGroups", customerGroups);

		//当前月份
		mv.addObject("currentMonth", StringUtils.isNotBlank(remindMonth) ? remindMonth : DateFormatUtils.format(new Date(), "yyyy-MM"));

		//车型
		List<CodeValue> vehicleBrands = commonsService.queryByCodeValueByType("vehicleBrand");
		vehicleService.prepareVehicleBrandForDealer(dealerNum, vehicleBrands);
		mv.addObject("vehicleBrands", vehicleBrands);


		//保养项目
		List<String> serviceRemindItems = commonsService.queryByCodeValueGroupByType("ServiceRemindEnabled");
		mv.addObject("serviceRemindItems", serviceRemindItems);

		//check promotion privilege
		dealerPromotionPrivilege.setDealerNum(dealerNum);
		dealerPromotionPrivilegeService.checkDealerSMSPrivilege(dealerPromotionPrivilege);
//		log.info(dealerPromotionPrivilege.getDealerNum() + " , " + dealerPromotionPrivilege.getHeaderquartersPromotion()+ " , " + dealerPromotionPrivilege.getNoPromotion() + " , " + dealerPromotionPrivilege.getCustomerizedPromotion());
		mv.addObject("dealerPromotionPrivilege", dealerPromotionPrivilege);

		return mv;
	}

	@RequestMapping("/list")
	@ResponseBody
	public Object list(PageList<Remind> pageList, Remind pojo) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		pageList.setParam(pojo);
		remindService.queryPage(pageList);

		ajaxResponse.setData(pageList);

		return ajaxResponse;
	}


	@RequestMapping("/sms/list")
	@ResponseBody
	public Object sendList(PageList<RemindSendInfo> pageList, RemindSendInfo pojo) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		pageList.setParam(pojo);
		remindSendInfoService.queryPage(pageList);

		ajaxResponse.setData(pageList);

		return ajaxResponse;
	}


	@RequestMapping("/consume/list")
	@ResponseBody
	/*public Object consumeList(PageList<ConsumeInfo> pageList, ConsumeInfo pojo) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		pageList.setParam(pojo);
		consumeInfoService.queryConsumeHistoryPage(pageList);

		ajaxResponse.setData(pageList);

		return ajaxResponse;
	}*/
	public Object consumeList(PageList<OrderInfo> pageList, OrderInfo pojo) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		pageList.setParam(pojo);
		saleOrderService.queryOrderInfoForPage(pageList);

		ajaxResponse.setData(pageList);

		return ajaxResponse;
	}


	@RequestMapping("/sms/review")
	@ResponseBody
	public Object reviewSms(RemindSmsReview remindSmsReview) {
		AjaxResponse ajaxResponse = new AjaxResponse();


//		if("ENABLED".equals(dealerPromotionPrivilege.getHeaderquartersPromotion()) || "ENABLED".equals(dealerPromotionPrivilege.getCustomerizedPromotion())){
//			remindSmsReview.setPromotionType("0");
//		}

		String sms = remindSendInfoService.getSmsContent(remindSmsReview, true, null, false);

		remindSmsReview.setSmsContent(sms);
		ajaxResponse.setData(remindSmsReview);

		return ajaxResponse;
	}




	@RequestMapping("/sms/sendAll")
	@ResponseBody
	public Object sendAll(RemindSmsReview remindSmsReview, Remind remind) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		PageList<Remind> pageList = new PageList<Remind>();
		pageList.setParam(remind);
		pageList.setLimit(Integer.MAX_VALUE);
		remindService.queryPage(pageList);

		//短信余额校验
//		Long smsQuantity = remindSmsService.querySmsQuantityByDealerNum(remindSmsReview.getDealerNum());
//
//		if(smsQuantity < pageList.getTotalCount()){
//			ajaxResponse.setSuccess(false);
//			ajaxResponse.setErrorCode("ERROR");
//			ajaxResponse.setMessage("短信余额不足<短信余额为" + smsQuantity + "，需要发送的短信为 " + pageList.getTotalCount() + ">，请先充值");
//
//		}else{
        	if(null != pageList.getItems()){
        		int i = 0;
        		for(; i < pageList.getItems().size(); i++) {
        			Remind rm = pageList.getItems().get(i);
        			if("是".equals(rm.getWechatMember())) {
        				pageList.getItems().remove(i);
        				i --;
        			}
        		}
        	}
            remindSendInfoService.createRemindSMS(remindSmsReview, pageList.getItems());
    		ajaxResponse.setMessage("操作成功，您本次总共发送" + pageList.getItems().size() + "条保养提醒信息");
//        }

		return ajaxResponse;
	}

	@RequestMapping("/sms/sendSelected")
	@ResponseBody
	public Object sendSelected(RemindSmsReview remindSmsReview, Remind remind, @RequestParam("srId") List<String> selectedIdList) {
		AjaxResponse ajaxResponse = new AjaxResponse();

		if(selectedIdList.isEmpty()){
			ajaxResponse.setSuccess(false);
			ajaxResponse.setErrorCode("ERROR");
			ajaxResponse.setMessage("请先选择要发送的客户.");

			return ajaxResponse;
		}


		PageList<Remind> pageList = new PageList<Remind>();
		pageList.setParam(remind);
		pageList.setLimit(Integer.MAX_VALUE);
		remindService.queryPage(pageList);

		//短信余额校验
//		Long smsQuantity = remindSmsService.querySmsQuantityByDealerNum(remindSmsReview.getDealerNum());
		List<Remind> remindList = new ArrayList<Remind>();
//
//		if(smsQuantity < selectedIdList.size()){
//			ajaxResponse.setSuccess(false);
//			ajaxResponse.setErrorCode("ERROR");
//			ajaxResponse.setMessage("短信余额不足<短信余额为" + smsQuantity + "，需要发送的短信为 " + pageList.getTotalCount() + ">，请先充值");
//		}else{
			for (Remind tmp : pageList.getItems()) {
				if(selectedIdList.contains(tmp.getServiceRemindId())){
					remindList.add(tmp);
				}
			}

            remindSendInfoService.createRemindSMS(remindSmsReview, remindList);

			ajaxResponse.setMessage("操作成功，您本次总共发送" + remindList.size() + "条保养提醒信息");

//		}


		return ajaxResponse;
	}


}
